using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public NodeMap map;
    private Rigidbody2D rb;
    private Animator anim;
   public int x;
    public int y;
    private Vector3 startpoint;
    public Vector3 nowpoint;
   public Vector3 nextpoint;
    public Vector3 move;
    private bool canmove;
    private void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
    }
    private void Start()
    {
        canmove = true;
        x = 0;
        y = 6;
        startpoint = map.nodeposition[x, y];
        nowpoint = startpoint;
        rb.MovePosition(startpoint);
    }
    private void Update()
    {
        if (canmove)
        {
            if (Input.GetKeyDown(KeyCode.W))
            {
                canmove = false;
                y = y + 1;
                nextpoint = map.nodeposition[x, y];

                Move();
            }
            if (Input.GetKeyDown(KeyCode.S))
            {
                canmove = false;
                y = y - 1;
                nextpoint = map.nodeposition[x, y];

                Move();
            }
            if (Input.GetKeyDown(KeyCode.A))
            {
                canmove = false;
                x = x - 1;
                nextpoint = map.nodeposition[x, y];

                Move();
            }
            if (Input.GetKeyDown(KeyCode.D))
            {
                canmove = false;
                x = x + 1;
                nextpoint = map.nodeposition[x, y];

                Move();
            }
        }
        
    }
    private void FixedUpdate()
    {
        StopMove();
    }
    private void Move()
    {
        move = nextpoint - nowpoint;
        rb.velocity =1f* move;
    }
    private void StopMove()
    {
        if((rb.transform.position-nextpoint).magnitude<0.01f)
        {
            canmove = true;
            rb.velocity = Vector2.zero;
            nowpoint = nextpoint;
        }
        
    }
}
